package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.mapper.OrderMapper;
import com.ruoyi.system.service.IOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-20
 */
@Service
public class OrderServiceImpl implements IOrderService
{
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id)
    {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order)
    {
        if (StringUtils.isNotBlank(order.getRoles())){
            if (order.getRoles().contains(UserConstants.ADMIN)){
                order.setShopId(null);
            }else if(order.getRoles().contains(UserConstants.COMMON)) {
                order.setUserId(SecurityUtils.getUserId());
            }
        }
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order)
    {
        order.setCreateTime(DateUtils.getNowDate());
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        order.setStatus(OrderStatusEnum.ORDER_WAIT_CONFIRM_SEND.getCode());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids)
    {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id)
    {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public void sendOrder(Long id) {
        Order order = new Order();
        order.setId(id);
        order.setStatus(OrderStatusEnum.ORDER_CONFIRM_SEND.getCode());
        orderMapper.updateOrderInfo(order) ;

    }

    @Override
    public void orderSuccess(Long id) {
        Order order = new Order();
        order.setId(id);
        order.setStatus(OrderStatusEnum.ORDER_SUCCESS.getCode());
        order.setEndTime(new Date());
        orderMapper.orderSuccess(order) ;
    }
}
